package com.wpre.lotterysystem.common.interceptor;

import com.wpre.lotterysystem.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created with IntelliJ IDEA.
 * Description: 定义登录拦截器
 * User: LianBao
 * Date: 2024-12-18
 * Time: 19:25
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 预处理,业务请求之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头(JWT是在Header中的)
        String token = request.getHeader("user_token");
        log.info("获取token");
        //解析token
        Claims claims = JWTUtil.parseJWT(token);
        if (claims == null) {
            log.error("令牌解析失败");
            response.setStatus(401);//设置状态码
            return false;
        }
        log.info("解析令牌成功,放行");
        return true;
    }
}
